package leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class LeetCode102 {

    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> tmp = new ArrayList<>();
        if (root == null)
            return lists;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        queue.add(new TreeNode(Integer.MIN_VALUE));
        while (true) {
            TreeNode node = queue.poll();
            //出现分界符号
            if (node.val == Integer.MIN_VALUE) {
                lists.add(tmp);
                if (queue.isEmpty())
                    break;
                else {
                    tmp = new ArrayList<>();
                    queue.add(new TreeNode(Integer.MIN_VALUE));
                    continue;
                }
            }
            tmp.add(node.val);
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);
        }
        return lists;
    }


    //可以使用递归来解题
    //依旧可以递归
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        helper(root, 0);
        return result;
    }

    private void helper(TreeNode node, int level) {
        if (node == null)
            return;
        if (result.size() == level)
            result.add(new ArrayList<>());
        result.get(level).add(node.val);
        helper(node.left, level + 1);
        helper(node.right, level + 1);
    }
//------------------------------------------------------------------
}
